//
//  RecommendViewController.m
//  Finder
//
//  Created by cdm on 11-3-16.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "RecommendViewController.h"
#import "ChildContentViewController.h"
#import "WebBrowserController.h"
#import "ContentCell.h"
#import "Content.h"
#import "DeviceUtil.h"

@interface RecommendViewController ()

@property (nonatomic, retain) NSMutableArray *recommendApps;

- (void)appLanguageDidChange;

@end

@implementation RecommendViewController

@synthesize recommendApps;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [self.recommendApps release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.recommendApps = [ApplicationContext sharedContext].recommendApps;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appLanguageDidChange) name:kAppLanguageChangedNotification object:nil];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    self.parentViewController.navigationItem.title = self.title;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [self.recommendApps count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    ContentCell *cell = (ContentCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        //cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
   
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"ContentCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    
    Content *child = [self.recommendApps objectAtIndex:indexPath.row];
    
    NSString *childName = child.name;
    int childType = child.type;
    
    cell.titleLabel.text = childName;
    
    if (child.icon != nil) {
        cell.leftIconImageView.image = [UIImage imageNamed:child.icon];
        [cell showLeftIcon:YES];
    } else {
        [cell showLeftIcon:NO];
    }
    
    if (childType == ContentTypeChildren) {
        UIImage *webImage = [UIImage imageNamed:@"ic_show_next.png"];
        cell.rightIconImageView.image = webImage;   
    } else if (childType == ContentTypeWeb) {
        UIImage *webImage = [UIImage imageNamed:@"ic_web.png"];
        cell.rightIconImageView.image = webImage;
    } else if (childType == ContentTypeSMS) {
        UIImage *webImage = [UIImage imageNamed:@"ic_sms.png"];
        cell.rightIconImageView.image = webImage;
    } else if (childType == ContentTypePhone) {
        UIImage *webImage = [UIImage imageNamed:@"ic_phone.png"];
        cell.rightIconImageView.image = webImage;
    } else if (childType == ContentTypeAppStore) {
        UIImage *webImage = [UIImage imageNamed:@"ic_store.png"];
        cell.rightIconImageView.image = webImage;
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Content *content = [self.recommendApps objectAtIndex:indexPath.row];
        
    int contentType = content.type;
    NSString *contentData = content.data;
    
    NSLog(@"Content view select content %@ at %d", content.name, indexPath.row); 
    
    
    if (contentType == ContentTypeChildren) {
        ChildContentViewController *childContentViewController = [[ChildContentViewController alloc] initWithNibName:@"ChildContentView" bundle:nil];
        childContentViewController.content = content;
        
        [self.navigationController pushViewController:childContentViewController animated:YES];
        [childContentViewController release];
    } else if (contentType == ContentTypeWeb) {
        WebBrowserController *webBrowserController = [[WebBrowserController alloc] initWithNibName:@"WebBrowser" bundle:nil];
        [webBrowserController loadWithURL:contentData];
        [self presentModalViewController:webBrowserController animated:YES];
        [webBrowserController release];
    } else if (contentType == ContentTypeSMS) {
        
        NSRange separaterRange = [contentData rangeOfString:@":"];
        NSString *recipient = nil;
        NSString *sms = nil;
        
        if (separaterRange.length > 0) {
            int separaterIndex = [contentData rangeOfString:@":"].location;
            
            recipient = [contentData substringToIndex:separaterIndex];
            sms = [contentData substringFromIndex:separaterIndex+1];
        } else {
            sms = contentData;
        }
        
        if ([DeviceUtil canSendSMS]) {
            
            MFMessageComposeViewController *messageController = [[MFMessageComposeViewController alloc] init];
            messageController.messageComposeDelegate = self;
            messageController.body = sms;
            messageController.recipients = [NSArray arrayWithObjects:recipient, nil];
            [self presentModalViewController:messageController animated:YES];
            [messageController release];
        } else {
            NSString *message = nil;
            if (recipient == nil) {
                message = [NSString stringWithFormat:@"您使用的设备无法发送短信，请使用手机发送:%@", sms];
            } else {
                message = [NSString stringWithFormat:@"您使用的设备无法发送短信，请使用手机发送:%@到%@", sms, recipient];
            }
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
        }

    } else if (contentType == ContentTypePhone) {
        if ([DeviceUtil canCallPhone]) {
            NSString *tel = [@"tel:" stringByAppendingString:contentData];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tel]];
        } else {
            NSString *message = [NSString stringWithFormat:@"您使用的设备无法拨打电话，请用手机拨打:%@", contentData];
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alertView show];
            [alertView release];
        }

    } else if (contentType == ContentTypeAppStore) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:contentData]];
    }     

}

#pragma mark - MFMessage compose delegate

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult)result
{
    [self dismissModalViewControllerAnimated:YES];
}

#pragma mark - App Language

- (void)appLanguageDidChange
{
    self.recommendApps = [ApplicationContext sharedContext].recommendApps;
    
    [self.tableView reloadData];
}

@end
